package ru.urfc.portal.ui.client.widgets;

import java.util.Date;

import ru.urfc.portal.ui.client.BaseGooglet;
import ru.urfc.portal.ui.client.Style;
import ru.urfc.portal.ui.client.Utils;
import ru.urfc.portal.ui.client.descriptor.CompositeGridField;
import ru.urfc.portal.ui.client.descriptor.GridDescriptor;
import ru.urfc.portal.ui.client.descriptor.GridField;
import ru.urfc.portal.ui.client.model.catalogs.DocumentState;
import ru.urfc.portal.ui.client.renderers.SimpleRenderer;

import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Widget;

public class DocumentHeader extends BaseGooglet {

	interface Binder extends UiBinder<Widget, DocumentHeader> {}
	private static Binder binder = GWT.create(Binder.class);
	
	private GridDescriptor descriptor;

	@UiField Style style;
	
	@UiField Element state;	
	@UiField TextField<String> outgoingNumber;
	@UiField DateField outgoingDate;
	@UiField Element incoming;	
	
	@Override
	protected void init() {
		initWidget(binder.createAndBindUi(this));
		
		descriptor = new GridDescriptor(DOCUMENT, CLIENTS, getClientId(), DOCUMENTS, getItemId());
		descriptor.addCIFields("state/text", "state/code", DocumentState.class, state, style);
		descriptor.addTextField("outgoingNumber", outgoingNumber);
		descriptor.addDateField("outgoingDate", outgoingDate);
		final CompositeGridField incomingFields = descriptor.addCompositeField("incomingNumber").addField(
				descriptor.addDateField("incomingDate"));
		descriptor.assign(new SimpleRenderer(incomingFields, incoming) {
			@Override
			public String render(ModelData modelData) {
				GridField numberField = incomingFields.getGridFields().get(0);
				GridField dateField = incomingFields.getGridFields().get(1);
				String number = numberField.getValue(modelData);
				Date date = dateField.getValue(modelData);
				return number == null && date == null? "": "Вх. №" + number + ", " + Utils.dateToStr(date);
			}
		});
	}
	
	public GridDescriptor getDescriptor() {
		return descriptor;
	}

}
